<?php

namespace app\bll;

use app\validate\Site as ValidateSite;
use Exception;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use support\Db;

/**
 * 站点
 */
class Site
{

    /**
     * 根据ID查找
     *
     * @param integer $id
     * @return array
     */
    public function find(int $id): array
    {
        $data =  Db::table('frame_site')
            ->where('id', '=', $id)
            ->first();
        return $data === null ? [] : get_object_vars($data);
    }

    /**
     * 根据IDENT查找
     *
     * @param string $ident
     * @return array
     */
    public function findByIdent(string $ident): array
    {
        $data =  Db::table('frame_site')
            ->where('ident', '=', $ident)
            ->first();
        return $data === null ? [] : get_object_vars($data);
    }


    /**
     * 查询站点
     *
     * @param integer $status
     * @return array
     */
    public function select(?int $status = null): array
    {
        return Db::table('frame_site')
            ->when($status !== null, function ($query) use ($status) {
                return $query->where('status', '=', $status);
            })
            ->get()
            ->map(function ($value) {
                return (array)$value;
            })
            ->toArray();
    }


    /**
     * 添加站点
     *
     * @param array $data
     * @return integer
     */
    public function add(array $data): int
    {
        $ValidateSite = new ValidateSite();
        if (!$ValidateSite->check($data)) {
            throw new Exception($ValidateSite->getSimpleError());
        }

        if ($this->findByIdent($data['ident'])) {
            throw new Exception('标识已存在');
        }

        if ($this->findByDomain($data['domain'])) {
            throw new Exception('域名已存在');
        }
        if (isset($data['orgid']) && !$data['orgid']) {
            unset($data['orgid']);
        }
        $data['statistics'] = htmlspecialchars_decode($data['statistics']);
        $data['icp']        = htmlspecialchars_decode($data['icp']);

        return Db::table('frame_site')
            ->insertGetId($data);
    }


    /**
     * 编辑
     *
     * @param integer $id
     * @param array $data
     * @return integer
     */
    public function edit(int $id, array $data): int
    {
        $ValidateSite = new ValidateSite();
        if (!$ValidateSite->check($data)) {
            throw new Exception($ValidateSite->getSimpleError());
        }

        $idetninfo = $this->findByIdent($data['ident']);
        if ($idetninfo && $idetninfo['id'] != $id) {
            throw new Exception('标识已存在');
        }

        $domaininfo = $this->findByDomain($data['domain']);

        if ($domaininfo && $domaininfo['id'] != $id) {
            throw new Exception('域名已存在');
        }
        if (isset($data['orgid']) && !$data['orgid']) {
            unset($data['orgid']);
        }
        $data['statistics'] = htmlspecialchars_decode($data['statistics']);
        $data['icp']        = htmlspecialchars_decode($data['icp']);
        return Db::table('frame_site')
            ->where('id', '=', $id)
            ->update($data);
    }


    /**
     * 一组ID查询站点
     *
     * @param integer $status
     * @return array
     */
    public function selectInIds(array|string $ids, ?int $status = null): array
    {
        if (is_string($ids)) {
            $ids = explode(',', $ids);
        }
        return Db::table('frame_site')
            ->when($status !== null, function ($query) use ($status) {
                return $query->where('status', '=', $status);
            })
            ->whereIn('id', $ids)
            ->get()
            ->map(function ($value) {
                return (array)$value;
            })
            ->toArray();
    }



    /**
     * 根据域名查询
     *
     * @param string $domain
     * @return array
     */
    public function findByDomain(string $domain): array
    {
        $data =  Db::table('frame_site')
            ->where('domain', '=', $domain)
            ->first();
        return $data === null ? [] : get_object_vars($data);
    }


    public function setStatus(int $id, int $status): int
    {
        return Db::table('frame_site')
            ->where('id', '=', $id)
            ->update(['status' => $status]);
    }



    /**
     * 分页查询
     *
     * @param string $name
     * @param string $ident
     * @param integer $pagesize
     * @return LengthAwarePaginator
     */
    public function paginator(
        int $pagesize = 20
    ): LengthAwarePaginator {
        return  Db::table('frame_site')
            ->orderBy('id', 'desc')
            ->paginate($pagesize);
    }
}
